﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Poet
{
    /// <summary>
    /// Property Name Provider.
    /// </summary>
    public class PropertyNameProvider
    {
        /// <summary>
        /// Gets the name of the property.
        /// </summary>
        /// <typeparam name="T">Property type.</typeparam>
        /// <param name="lambdaExpression">The lambda expression like '() => Property'.</param>
        /// <returns>The name of the property.</returns>
        public static string GetPropertyName<T>(Expression<Func<T>> lambdaExpression)
        {
            var memberExpression = lambdaExpression.Body as MemberExpression;
            var unaryExpression = lambdaExpression.Body as UnaryExpression;

            if (unaryExpression != null)
            {
                memberExpression = unaryExpression.Operand as MemberExpression;
            }

            if (memberExpression == null || memberExpression.Member.MemberType != MemberTypes.Property)
            {
                throw new Exception("Invalid lambda expression format.");
            }

            return memberExpression.Member.Name;
        }
    }
}
